const router = require('koa-router')()
const User = require('./../modules/UserSchema')
const Menu = require('./../modules/MenusSchema')
const Role = require('./../modules/RoleSchema')
const util = require('./../utils/util.js')
const jwt = require('jsonwebtoken')
const Counter = require('./../modules/CounterSchema')
const md5 = require('md5')
router.prefix('/users')
// 登錄
router.post('/login', async (ctx) => {
  const { userName, userPwd } = ctx.request.body
  try {
    const result = await User.findOne(
      {
        userName,
        userPwd: md5(userPwd),
      },
      'userId userName userEmail state role deptId roleList job call imgUrl'
    )
    const token = jwt.sign(
      {
        data: result,
      },
      'abizuis',
      { expiresIn: '6h' }
    )
    if (result) {
      let data = result._doc
      data['token'] = token
      ctx.body = util.success(data)
    } else {
      ctx.body = util.fail('账号或密码错误')
    }
  } catch (e) {
    ctx.body = util.fail(e.msg)
  }
})
// 用戶列表
router.get('/list', async (ctx) => {
  const { userId, userName, state } = ctx.request.query
  const { page, skipIndex } = util.pager(ctx.request.query)
  let params = {}
  if (userId) params.userId = userId
  if (userName) params.userName = userName
  if (state && state != 0) params.state = state
  try {
    const query = User.find(params, { _id: 0, userPwd: 0 })
    const list = await query.skip(skipIndex).limit(page.pageSize)
    const total = await User.countDocuments(params)
    ctx.body = util.success(
      {
        page: {
          ...page,
          total,
        },
        list,
      },
      '查詢成功'
    )
  } catch (error) {
    util.fail(`网络异常!`)
  }
})
// 用户删除:更新为离职
router.post('/delete', async (ctx) => {
  const { userId } = ctx.request.body
  //User.updateMany($or:[{userId:10001},{userId:1002}],{satate:2})
  const res = await User.updateMany({ userId: { $in: userId } }, { state: 2 })
  if (res.nModified) {
    ctx.body = util.success(res, `删除成功${res.nModified}条`)
    return
  }
  ctx.body = util.fail('删除失败')
})
// 用户编辑,添加 action:add OR edit
router.post('/operate', async (ctx) => {
  const {
    userId,
    userName,
    userEmail,
    mobile,
    job,
    imgUrl,
    call,
    state,
    roleList,
    deptId,
    action,
  } = ctx.request.body
  if (action == 'add') {
    if (!userName || !userEmail || !deptId) {
      ctx.body = util.fail('参数错误', util.CODE.PARAM_ERROR)
      return
    }
    const res = await User.findOne(
      { $or: [{ userName }, { userEmail }] },
      '_id userName userEmail'
    )
    if (res) {
      ctx.body = util.fail(`系统检测已存在用户${userName}--${userEmail}`)
    } else {
      // 更新自增长+1
      const doc = await Counter.findOneAndUpdate(
        { _id: 'userId' },
        { $inc: { sequence_value: 1 } },
        { new: true }
      )
      try {
        const user = new User({
          userId: doc.sequence_value,
          userName,
          userPwd: md5('123456'),
          userEmail,
          role: 1,
          roleList,
          job,
          imgUrl,
          call,
          state,
          deptId,
          mobile,
        })
        user.save()
        ctx.body = util.success('ok', '用户创建成功')
      } catch (error) {
        ctx.body = util.fail(`异常:${error.stack}`)
      }
    }
  } else {
    if (!deptId) {
      ctx.body = util.fail('部门不得为空', util.CODE.PARAM_ERROR)
      return
    }
    try {
      const res = await User.findOneAndUpdate(
        { userId },
        { mobile, job, imgUrl, call, state, roleList, deptId }
      )
      ctx.body = util.success('Ok!', '更新成功')
    } catch (error) {
      ctx.body = util.fail(error.stack)
    }
  }
})
router.get('/all/list', async (ctx) => {
  const list = await User.find({})
  ctx.body = util.success(list, '请求成功')
})
// 用户对应权限菜单
router.get('/getroleList', async (ctx) => {
  const auth = ctx.request.headers.authorization
  const token = auth.split(' ')[1]
  const { data } = jwt.verify(token, 'abizuis')
  let menuList = await getMenuList(data.role, data.roleList)
  let actionList = getActionList(JSON.parse(JSON.stringify(menuList)))
  ctx.body = util.success({ menuList, actionList })
})

// 权限菜单初始化
async function getMenuList(userRole, roleKeys) {
  let rootList = []
  if (userRole == 0) {
    // 管理员获取全部菜单
    rootList = (await Menu.find({})) || []
  } else {
    // 根据用户拥有的角色,获取权限列表
    // 先查找用户对应的角色有哪些,然后对菜单去重
    let roleList = await Role.find({ _id: { $in: roleKeys } })
    let permissionList = []
    // 查找菜单
    roleList.map((role) => {
      let { checkedKeys, halfCheckedKeys } = role.permissionList
      permissionList = permissionList.concat([
        ...checkedKeys,
        ...halfCheckedKeys,
      ])
    })
    // 去重
    permissionList = [...new Set(permissionList)]
    rootList = await Menu.find({ _id: { $in: permissionList } })
  }
  return util.getTreeMenu(rootList, null, [])
}
// 按钮权限分配
function getActionList(list) {
  let actionList = []
  const deep = (array) => {
    while (array.length) {
      let item = array.pop()
      if (item.action) {
        item.action.map((action) => {
          actionList.push(action.menuCode)
        })
      } else if (item.children && !item.action) {
        deep(item.children)
      }
    }
  }
  deep(list)
  return actionList
}
module.exports = router
